package tv.youxing.android.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.List;

import tv.youxing.android.MainActivity;
import tv.youxing.android.R;
import tv.youxing.android.entity.MyInfoModel;
import tv.youxing.android.utils.AppConst;
import tv.youxing.android.utils.GsonUtils;
import tv.youxing.android.utils.ShareUtils;
import tv.youxing.android.utils.StaticClass;
import tv.youxing.android.utils.UtilTools;

import static com.mob.MobSDK.getContext;

/**
 * 新版 视频 的欢迎界面
 */
public class VideoWelcomeActivity extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener{

    SurfaceView mv_play;
    SurfaceHolder surfaceHolder;
    MediaPlayer mp;
    TextView tvSkip;//跳过


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            // 把视频画面输出到SurfaceView
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mp.setDisplay(holder);
            //mp.prepare(); //缓冲。 如果获得本地raw下的视频文件,不能写这个方法，不然会报错。
            mp.start();
        } catch (Exception e) {
//            Log.e("err", e.toString());
        }
        mp.setOnPreparedListener(this);
        mp.setOnCompletionListener(this);

    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        if (mp != null) {
            mp.release(); //释放内存
        }
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        if (!ShareUtils.getBoolean(this, AppConst.ISGUIDE, false)) {
            startActivity(new Intent(this,GuideActivity.class));
            finish();
            return;
        }

        setContentView(R.layout.activity_video_welcome);
        tvSkip = (TextView) findViewById(R.id.mv_finish);
        mv_play = (SurfaceView) findViewById(R.id.mv_play);

        //解决SurfaceView闪屏的问题
        mv_play.setZOrderOnTop(true);
        mv_play.getHolder().setFormat(PixelFormat.TRANSLUCENT);



        mp = MediaPlayer.create(getApplicationContext(), R.raw.welcomee);//获取raw下的视频文件
        surfaceHolder = mv_play.getHolder(); // SurfaceHolder是SurfaceView的控制接口
        surfaceHolder.addCallback(this);// 因为这个类实现了SurfaceHolder.Callback接口，所以回调参数直接this
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        tvSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mp != null) {
                    mp.stop();
                    mp.release();//释放内存
                    mp = null;
                }
                startActivity(new Intent(VideoWelcomeActivity.this, MainActivity.class));
                finish();
            }
        });
    }




    /**
     * 缓冲，准备工作
     */
    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {

    }

    /**
     * 播放结束
     */
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
//        CustomToast.INSTANCE.showToast("播放结束");


        getAuthority();
    }


    void getAuthority() {
        // 申请多个权限。
        AndPermission.with(this)
                .requestCode(100)
                .permission(Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
                .callback(mPermissionListener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(VideoWelcomeActivity.this, rationale)
                                .show();
                    }
                })
                .start();
    }


    /**
     * 申请权限回调
     */
    PermissionListener mPermissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == 100) {
//                Toast.makeText(VideoWelcomeActivity.this,"设置成功", Toast.LENGTH_LONG).show();

                //

//                startActivity(new Intent(VideoWelcomeActivity.this, MainActivity.class));
//                finish();

                requestUserData();
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == 100) {
                // 是否有不再提示并拒绝的权限。
                if (AndPermission.hasAlwaysDeniedPermission(VideoWelcomeActivity.this, deniedPermissions)) {
                    // 第一种：用AndPermission默认的提示语。
                    AndPermission.defaultSettingDialog(VideoWelcomeActivity.this, 400).show();
                } else {
                    getAuthority();
                }
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 400: {
//                Toast.makeText(this,"设置成功", Toast.LENGTH_LONG).show();
//                startActivity(new Intent(VideoWelcomeActivity.this, MainActivity.class));
//                finish();
                requestUserData();
                break;
            }
        }
    }


    /**
     * 请求用户信息 用来判断token是否过期
     */
    void requestUserData() {


        if (!UtilTools.LoginJudge()) {
            startActivity(new Intent(VideoWelcomeActivity.this, MainActivity.class));
            finish();
            return;
        }

        HttpParams params = new HttpParams();
        params.putHeaders("Authorization","Bearer "+ ShareUtils.getString(getContext(),AppConst.TOKEN,""));


        RxVolley.post(StaticClass.MyInfo, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {

                MyInfoModel mMyInfoModel = GsonUtils.GsonToBean(t,MyInfoModel.class);



                if (mMyInfoModel.getCode() == 200) {
                    startActivity(new Intent(VideoWelcomeActivity.this, MainActivity.class));
                    finish();
                } else if (mMyInfoModel.getCode() == AppConst.TOKENERROR) {
                    startActivity(new Intent(VideoWelcomeActivity.this, LoginActivity.class));
                    finish();
                }
            }
        });
    }
}


